<!DOCTYPE html>
<html>
<head></head>
<script type="text/javascript" src="b.js"></script>
<script type="text/javascript" src="md5.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<body>
<script>
	var uid, tid;
    var displayingKeys = {};

	//Amazon Item URL:
	//"http://www.amazon.cn/PNY-%E5%BF%85%E6%81%A9%E5%A8%81-%E7%86%8A%E7%8C%AB2%E4%BB%A3%E7%B2%BE%E8%A3%85%E7%89%88-32GB-%E4%BC%98%E7%9B%98/dp/B003PDOI52/ref=sr_1_15?s=pc&ie=UTF8&qid=1306135697&sr=1-15"

	//set uid to identify each user with extension installed.
	if (localStorage.uid == null) {
		uid = guid();
		localStorage.uid = uid;
	}
	else {
		uid = localStorage.uid;
	}

	function S4() {
	   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	}

	function guid() {
	   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
	}
    var tkurl = 'http://gw.api.tbsandbox.com/router/rest?sign=3737352221BE1608A8258CA5E97ECC66&timestamp=2011-05-27+14%3A34%3A14&v=2.0&app_key=12129701&method=taobao.taobaoke.items.convert&partner_id=top-apitools&format=xml&nick=yamone&outer_code=chrome&num_iids=8655943042&fields=click_url,num_iid,commission,commission_rate,commission_num,commission_volume';
    tkurl = 'http://gw.api.tbsandbox.com/router/rest?sign=E9788C94D9D80904CEB4A9C4CDA283BB&timestamp=2011-05-27+14%3A45%3A42&v=2.0&app_key=12129701&method=taobao.taobaoke.items.convert&partner_id=top-apitools&format=json&nick=yamone&outer_code=chrome&num_iids=1451792607&fields=click_url,num_iid,commission,commission_rate,commission_num,commission_volume';
    //tkurl = 'http://gw.api.taobao.com/router/rest?sign=9E1E66D9CAA425D2DCC17EF7D6302CA1&timestamp=2011-05-27+14%3A52%3A24&v=2.0&app_key=12152946&method=taobao.taobaoke.items.convert&partner_id=top-apitools&format=json&nick=yamone&outer_code=chrome&num_iids=8655943042&fields=click_url,num_iid,commission,commission_rate,commission_num,commission_volume';

    function fetch(method, url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(data) {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    console.log(xhr.responseText);
                    var data = xhr.responseText;
                    callback(data);
                } else {
                    callback(null);
                }
            }
        }

        xhr.open(method, url, true);
        xhr.send();
    }

    function fetchAppleStoreItemPage(callback) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(data) {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var data = xhr.responseText;
                    callback(data);
                } else {
                    callback(null);
                }
            }
        }
        // Note that any URL fetched here must be matched by a permission in
        // the manifest.json file!
        var url = 'http://store.apple.com/cn/browse/home/shop_ipad/family/ipad/select?mco=MjE2MjYyNzA';
        url = 'http://searchjob.chinahr.com/api/websearch.asmx?op=Search';
        xhr.open('GET', url, true);
        xhr.send();
    };

    function addItem(item) {
        var items = {};
        var k = hex_md5(item.url);
        item.notified = false;

        if (localStorage.drItems != null) {
            items = JSON.parse(localStorage.drItems);
        }
        items[k] = item;

        localStorage.drItems = JSON.stringify(items);
    }

    function closeNotification (key) {
        var items = getItems();
        items[key].notified = true;
        localStorage.drItems = JSON.stringify(items);
        delete displayingKeys[key];
    }

    function init() {
    	if (localStorage.drAvailableSites == null) {
    		localStorage.drAvailableSites = "www.360buy.com,www.amazon.cn,searchjob.chinahr.com,www.baidu.com";
    	}
        autoMonitor();
        if (tid == null) {
//            tid = setInterval('autoMonitor()', 1000*15);
        }
    }

    function autoMonitor() {
        var items = getItems();

        for (k in items) {
            var item = items[k];
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function(data) {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        var p = parsePrice({ "site": item.site, "html": xhr.responseText });
                        if (p < item.priceline) {
                            var notifier = webkitNotifications.createNotification(
                                'images/y_bag_48.png',
                                'price is drop',
                                "The item's price is drop, url: <a href='" + item.url + "' target='_blank'>查看</a>"
                            );

                            notifier.onclose = function() {
                                closeNotification(k);
                            };

                            if (!item.notified && displayingKeys[k] == null) {
                                notifier.show();
                                displayingKeys[k] = true;
                            }
                        }
                    } else {
                        console.log("webpage exception");
                    }
                }
            }

            xhr.open('GET', item.url, true);
            xhr.send();
        }

        tid = setTimeout(autoMonitor, 15*1000);
    }

    function parsePrice (data) {
        var pattern;
        if (data.site == "www.360buy.com") {
            pattern = /￥(\d{0,9}\.\d{0,2})。/g;
            result = pattern.exec(data.html);
            if (result != null) {
                return parseInt(result[1]);
            }
        }
    }

    function onRequest(request, sender, callback) {
    	switch(request.action) {
	        case "addItem":
                addItem(request.data);
	            break;
	        case "load":
                callback({ "drAvailableSites" : localStorage.drAvailableSites, "uid" : localStorage.uid });
	            break;
            case "tk":
                //fetch('GET', tkurl, callback);
                break;
            default:
                callback();
                break;
    	}
    };

    init();
    //getItemCode("http://www.360buy.com/product/383809.html", "");
    // Wire up the listener.
    chrome.extension.onRequest.addListener(onRequest);
    </script>
  </body>
</html>